package com.winai.launcher.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.baidu.location.BDLocation;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.base.BaseRecAdapter;
import com.winai.launcher.base.BaseRecViewHolder;
import com.winai.launcher.bean.WeatherBean;
import com.winai.launcher.bean.db.CurrentLocation;
import com.winai.launcher.bean.responseEntity.CityEntity;
import com.winai.launcher.bean.responseEntity.MojiEntity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.manager.BdLocationManager;
import com.winai.launcher.manager.WeatherManager;
import com.winai.launcher.override.LineChartView;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.PicassoLoadUtils;
import com.winai.launcher.utils.MathUtils;
import com.winai.launcher.utils.WeatherIconUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WeatherActivity extends BaseActivity {

    @BindView(R.id.iv_loading)
    ImageView ivLoading;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    @BindView(R.id.line_chart_view)
    LineChartView mLineChartView;
    @BindView(R.id.tv_currentT)
    TextView tvCurrentT;//当前温度
    @BindView(R.id.tv_currentWeather)
    TextView tvCurrentWeather;//天气。例如：晴转多云
    @BindView(R.id.tv_currentWind)
    TextView tvCurrentWind;//风力

    private Context mContext = this;
    private WeatherAdapter weatherAdapter;
    private CurrentLocation currentLocation1 = new CurrentLocation();
    private final int RESULT_CODE = 0x1215;
    private Animation loadingAnimation;
    private final String TAG = "WeatherActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        showProgressBar();
        initObject();
        initView();
        initListener();

        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                mLineChartView.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.VISIBLE);
            }
        }, 1000);
    }

    private void initObject() {
        loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        loadingAnimation.setInterpolator(new LinearInterpolator());
    }

    private void initView() {
        strTitle.setText("天气中心");
        //加载天气缓存
        MojiEntity mojiEntity = WeatherManager.getInstance(mContext).getMojiEntity();
        if (mojiEntity != null) {
            updateViewData(mojiEntity);

            String city = mojiEntity.getCity();
            String province = mojiEntity.getProvince() == null
                    ? city.replace("市", "")
                    : mojiEntity.getProvince();
            String area = mojiEntity.getArea();
            String loc;
            if (!province.equals(city) && !TextUtils.isEmpty(area)) {
                loc = province + "-" + city + "-" + area;
            } else if (!province.equals(city)) {
                loc = province + "-" + city;
            } else {
                loc = city + "-" + area;
            }
            tvLocation.setText(loc);
        }
        requestBaiduLocation();
    }

    private void initListener() {
        GlobalPublisher.setListener(GlobalPublisher.WEATHER_UPDATE_FOR_WEATHER_CENTER, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                //更新天气信息
                MojiEntity mojiEntity = WeatherManager.getInstance(mContext).getMojiEntity();
                if (mojiEntity != null) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            updateViewData(mojiEntity);
                        }
                    });
                }
            }
        });

        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (recyclerView.getVisibility() == View.VISIBLE) {
                    hidingProgressBar();
                }
            }
        });
    }

    private void initRecyclerView(int size) {
        //指定列表线性布局，横向水平
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, size));
        weatherAdapter = new WeatherAdapter();
        LRecyclerViewAdapter mLRecyclerViewAdapter = new LRecyclerViewAdapter(weatherAdapter);
        recyclerView.setAdapter(mLRecyclerViewAdapter);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadMoreEnabled(false);
    }

    private void requestBaiduLocation() {
        BdLocationManager.getInstance().onStart(location -> {
            if (location == null) {
                Log.e(TAG, "获取位置失败，当前信息可能有误");
                return;
            }
            if (location.getLocType() == BDLocation.TypeCriteriaException) {
                Log.e(TAG, "获取位置失败，当前信息可能有误");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                Log.e(TAG, "获取位置失败，当前信息可能有误");
            } else {
                //获取经度信息
                double longitude = location.getLongitude();
                //获取维度信息
                double latitude = location.getLatitude();
                if (longitude == 0 || latitude == 0 || longitude == 4.9E-324 || latitude == 4.9E-324) {
                    Log.e(TAG, "获取位置失败，当前信息可能有误");
                    return;
                }
                String city = !TextUtils.isEmpty(location.getAddress().city)
                        ? location.getAddress().city
                        : "";
                String province = TextUtils.isEmpty(location.getAddress().province)
                        ? city.replace("市", "")
                        : location.getAddress().province;
                String district = !TextUtils.isEmpty(location.getAddress().district)
                        ? location.getAddress().district
                        : "";
                String loc;
                if (!province.equals(city)) {
                    loc = province + "-" + city + "-" + district;
                } else {
                    loc = city + "-" + district;
                }
                tvLocation.setText(loc);
                // 请求墨迹天气接口
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        WeatherManager.getInstance(mContext).requestMoji(province, city, district);
                    }
                }).start();
                //获取经纬度位置信息，存入本地数据库缓存
                currentLocation1.setLatitude(latitude);
                currentLocation1.setLongitude(longitude);
                currentLocation1.setAdminArea(province);
                currentLocation1.setLocality(city);
                currentLocation1.setSubLocality(district);
                currentLocation1.saveOrUpdate("id = 1");
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void updateViewData(MojiEntity mojiEntity) {
        if (mojiEntity == null) {
            return;
        }
        tvCurrentT.setText(mojiEntity.getCondition().getTemp());
        tvCurrentWeather.setText(mojiEntity.getCondition().getCondition() + "，");
        tvCurrentWind.setText(mojiEntity.getCondition().getWindLevel() + "级风");
        /*未来五天数据*/
        List<MojiEntity.FutureBean> future = mojiEntity.getFuture();
        int length = Math.min(future.size(), 5);
        initRecyclerView(length);
        List<WeatherBean> weatherBeanList = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            MojiEntity.FutureBean futureBase = future.get(i);
            String date = futureBase.getDate();
            String day;
            switch (i) {
                case 0:
                    day = "今天";
                    break;
                case 1:
                    day = "明天";
                    break;
                case 2:
                    day = "后天";
                    break;
                default:
                    day = BaseUtils.dateToWeek(date);
                    break;
            }
            String dateSub = date.substring(5);//日期
            String dateReplace = dateSub.replace("-", "/");

            int maxTmp = Integer.parseInt(mojiEntity.getFuture().get(i).getHighTemp());
            int minTmp = Integer.parseInt(mojiEntity.getFuture().get(i).getLowTemp());

            weatherBeanList.add(new WeatherBean(futureBase.getWeather(), day, dateReplace, maxTmp, minTmp));
        }
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                weatherAdapter.refreshData(weatherBeanList);
                initLineChartView(weatherBeanList);
            }
        });
    }

    /**
     * 说明：加载折线图
     *
     * @param weatherBeanList
     */
    private void initLineChartView(List<WeatherBean> weatherBeanList) {
        List<LineChartView.Data> datas = new ArrayList<>();
        for (int i = 0; i < weatherBeanList.size(); i++) {
            LineChartView.Data data = new LineChartView.Data(weatherBeanList.get(i).getAvg(), weatherBeanList.get(i).getMax(), weatherBeanList.get(i).getMin());
            datas.add(data);
        }
        mLineChartView.setData(datas);
        mLineChartView.setRulerYSpace(1);
        mLineChartView.setStepSpace((int) MathUtils.divide(1024, weatherBeanList.size(), 2));
        mLineChartView.setBezierLine(false);
        mLineChartView.setCubePoint(false);
    }

    @OnClick({R.id.iv_back_white, R.id.iv_home_white, R.id.tv_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back_white:
                finish();
                break;
            case R.id.iv_home_white:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.tv_location:
                // 跳转天气二级页面
                Intent intent = new Intent(mContext, LocationActivity.class);
                startActivityForResult(intent, RESULT_CODE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case RESULT_CODE:
                    if (data != null) {
                        //是否定位当前位置
                        boolean locationCurrent = data.getBooleanExtra("locationCurrent", true);
                        if (locationCurrent) {
                            requestBaiduLocation();
                        } else {
                            CityEntity.HeWeather6Bean.BasicBean bean =
                                    (CityEntity.HeWeather6Bean.BasicBean) data.getSerializableExtra("BasicBean");
                            if (bean != null) {
                                String location;
                                if (!bean.getAdmin_area().equals(bean.getParent_city()) && !bean.getParent_city().equals(bean.getLocation())) {
                                    location = bean.getAdmin_area() + "-" + bean.getParent_city() + "-" + bean.getLocation();
                                } else if (!bean.getAdmin_area().equals(bean.getParent_city()) && bean.getParent_city().equals(bean.getLocation())) {
                                    location = bean.getAdmin_area() + "-" + bean.getParent_city();
                                } else if (bean.getAdmin_area().equals(bean.getParent_city()) && !bean.getParent_city().equals(bean.getLocation())) {
                                    location = bean.getParent_city() + "-" + bean.getLocation();
                                } else {
                                    location = bean.getLocation();
                                }
                                tvLocation.setText(location);

                                String city = !TextUtils.isEmpty(bean.getParent_city())
                                        ? bean.getParent_city()
                                        : "";
                                String province = TextUtils.isEmpty(bean.getAdmin_area())
                                        ? city.replace("市", "")
                                        : bean.getAdmin_area();
                                String district = !TextUtils.isEmpty(bean.getLocation())
                                        ? bean.getLocation()
                                        : "";
                                // 请求墨迹天气接口
                                WeatherManager.getInstance(mContext).requestMoji(province, city, district);
                            }
                        }
                    }
                    break;
            }
        }
    }

    public void showProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ivLoading.startAnimation(loadingAnimation);
                ivLoading.setVisibility(View.VISIBLE);
            }
        });
    }

    public void hidingProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ivLoading.clearAnimation();
                ivLoading.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private class WeatherAdapter extends BaseRecAdapter<WeatherBean, WeatherAdapter.ViewHolder> {
        @SuppressLint("SetTextI18n")
        @Override
        public void onHolder(ViewHolder holder, WeatherBean bean, int position) {
            TextView tv_day = holder.getView(R.id.tv_day);
            TextView tv_date = holder.getView(R.id.tv_date);
            ImageView iv_weather = holder.getView(R.id.iv_weather);
            tv_day.setText(bean.getDay());
            tv_date.setText(bean.getDate());
            PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(WeatherIconUtil.getImgByName(bean.getCond_code()), iv_weather);
        }

        @Override
        public ViewHolder onCreateHolder() {
            return new ViewHolder(getViewByRes(R.layout.item_weather));
        }

        private class ViewHolder extends BaseRecViewHolder {
            ViewHolder(View itemView) {
                super(itemView);
            }
        }
    }
}
